package com.cucn.ingmall.ware.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.TypeReference;
import com.cucn.common.utils.R;
import com.cucn.ingmall.ware.feign.MemberFeignService;
import com.cucn.ingmall.ware.vo.FareVO;
import com.cucn.ingmall.ware.vo.MemberAddressVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cucn.common.utils.PageUtils;
import com.cucn.common.utils.Query;

import com.cucn.ingmall.ware.dao.WareInfoDao;
import com.cucn.ingmall.ware.entity.WareInfoEntity;
import com.cucn.ingmall.ware.service.WareInfoService;

import javax.annotation.Resource;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
    @Resource
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 条件查询仓库列表
     *
     * @param params 请求参数
     * @return 分页仓库数据
     */
    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        //可以根据id，地址，名称，编码进行条件查询
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("id", key)
                    .or().like("name", key)
                    .or().like("address", key)
                    .or().like("areacode", key);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据用户收货地址计算运费
     *
     * @param addrId 收货地址id
     * @return
     */
    @Override
    public FareVO getFare(Long addrId) {
        FareVO fareVO = new FareVO();
        //首先根据收货地址id远程调用查询收货地址详细信息
        R rMemberAddress = memberFeignService.addrInfo(addrId);
        MemberAddressVO memberReceiveAddress = rMemberAddress.getData("memberReceiveAddress", new TypeReference<MemberAddressVO>() {
        });
        if (ObjectUtil.isNotEmpty(memberReceiveAddress)) {
            //模拟运费效果
            String phone = memberReceiveAddress.getPhone();
            String s = phone.substring(phone.length() - 1);
            fareVO.setAddress(memberReceiveAddress);
            fareVO.setFare(new BigDecimal(s));
            return fareVO;
        }

        return null;
    }
}